package cc.cc4414.cc02.system.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cc.cc4414.cc02.core.result.ResultEnum;
import cc.cc4414.cc02.core.result.ResultException;
import cc.cc4414.cc02.system.entity.Authority;
import cc.cc4414.cc02.system.entity.Resource;
import cc.cc4414.cc02.system.repository.AuthorityRepository;
import cc.cc4414.cc02.system.repository.ResourceRepository;
import cc.cc4414.cc02.system.service.ResourceService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cc 2018年7月25日
 */
@Service
@Slf4j
public class ResourceServiceImpl implements ResourceService {

	@Autowired
	private ResourceRepository resourceRepository;

	@Autowired
	private AuthorityRepository authorityRepository;

	@Override
	public List<Resource> findAll() {
		return resourceRepository.findAllByOrderByUrlDesc();
	}

	@Override
	public List<Authority> findAuthorityByResourceId(Long resourceId) {
		return authorityRepository.findByResourceId(resourceId);
	}

	@Override
	public void save(Resource resource) {
		resource.setId(null);
		resourceRepository.save(resource);
	}

	@Override
	public void delete(Long resourceId) {
		if (!resourceRepository.findById(resourceId).isPresent()) {
			log.warn("id为{}的资源不存在", resourceId);
			throw new ResultException(ResultEnum.RESOURCE_NOT_EXIST);
		}
		resourceRepository.deleteResourceAuthorityByResourceId(resourceId);
		resourceRepository.deleteById(resourceId);
	}

	@Override
	public void updateResourceAuthority(Long resourceId, Long[] authorityIds) {
		if (!resourceRepository.findById(resourceId).isPresent()) {
			log.warn("id为{}的资源不存在", resourceId);
			throw new ResultException(ResultEnum.RESOURCE_NOT_EXIST);
		}
		resourceRepository.deleteResourceAuthorityByResourceId(resourceId);
		if (authorityIds == null) {
			return;
		}
		for (Long authorityId : authorityIds) {
			resourceRepository.saveResourceAuthorityByResourceIdAndAuthorityId(resourceId, authorityId);
		}
	}

	@Override
	public void update(Resource resource) {
		if (!resourceRepository.findById(resource.getId()).isPresent()) {
			log.warn("id为{}的资源不存在", resource.getId());
			throw new ResultException(ResultEnum.RESOURCE_NOT_EXIST);
		}
		resourceRepository.save(resource);
	}

}
